﻿var wamsUI =
    {
        Deployments:
            {
                Collection: [],
                GetUI: function (deplId)
                { return $("#dashboardDeploymentHeader>th.deplheader[data-deply-id='" + deplId + "']")[0]; },
                AddUI: function (depl)
                {
                    var deploymentUI = $("<th class='deplheader' data-deply-id='" + depl.Id + "' data-original-title='" + depl.Id + "'></th>");
                    $("#dashboardDeploymentHeader").append(deploymentUI);
                    wamsUI.Deployments.Collection.push(depl);
                    return deploymentUI;
                },
                RemoveUI: function (deplId) {
                    // Remove from list
                    for (var i = 0; i < wamsUI.Deployments.Collection.length; i++) {
                        var depl = wamsUI.Deployments.Collection[i];
                        if (depl.Id == deplId) {
                            wamsUI.Deployments.Collection.splice(i, 1);
                            break;
                        }
                    }
                    $(this.GetUI(deplId)).remove();
                },
                GetInstanceIndex: function(deplId)
                {
                    var index = 0;
                    var deplItems = $("#dashboardDeploymentHeader>th.deplheader");
                    for (var i = 0; i < deplItems.length; i++) {
                        if ($(deplItems[i]).attr("data-deply-id") == deplId) break;
                        index += parseInt($(deplItems[i]).attr("colspan"));
                    }
                    return index;
                }
            },

        Instances:
            {
                Collection: [],
                GetRelatedCells: function(deplId, instanceId)
                {
                    var cells = [];
                    cells.push(wamsUI.Instances.GetUI(deplId, instanceId));
                    var stateCells = wamsUI.SiteStates.GetUIsForInstance(deplId, instanceId);
                    for (var i = 0; i < stateCells.length; i++) {
                        cells.push(stateCells[i]);
                    }
                    return cells;
                },
                GetUI: function (deplId, instanceId)
                { return $("th.instance[data-inst-id='" + instanceId + "'][data-depl-id='" + deplId + "']")[0]; },
                AddUI: function (instance) {
                    var instanceStatusInfo = GetInstanceStatusInfo(instance.Status);
                    var instColCell = $("\
<th class='instance updatable' data-inst-id='" + instance.Id + "' data-depl-id='" + instance.Deployment.Id + "' data-original-title='" + instance.Id + ": " + instanceStatusInfo.Title + "'>\
    <i class='icon-hdd "+instanceStatusInfo.CssClass+"'></i>\
</th>");
                    
                    instColCell.click(function () { toggleInstanceBusy(instance.Deployment.Id, instance.Id); });

                    instColCell.hover(
                        function () { $(wamsUI.Instances.GetRelatedCells(instance.Deployment.Id, instance.Id)).addClass("instancehover"); },
                        function () { $(wamsUI.Instances.GetRelatedCells(instance.Deployment.Id, instance.Id)).removeClass("instancehover"); }
                        );

                    var insertIndex = wamsUI.Deployments.GetInstanceIndex(instance.Deployment.Id);
                    $("#dashboardHeader").children("th:nth-child(" + (insertIndex + 2) + ")").after(instColCell);

                    wamsUI.Instances.Collection.push(instance);

                    for (var i = 0; i < wamsUI.Sites.Collection.length; i++) {
                        wamsUI.SiteStates.AddUI({
                            InstanceId: instance.Id,
                            DeploymentId: instance.Deployment.Id,
                            SiteId: wamsUI.Sites.Collection[i].Id
                        });
                    }

                    return instColCell;
                },
                RemoveUI: function(deploymentId,instanceId)
                {
                    var ui = wamsUI.Instances.GetUI(deploymentId, instanceId);
                    if (ui == null) return;

                    // Remove from header
                    $(ui).remove();

                    // Remove from instances list
                    for (var i = 0; i < wamsUI.Instances.Collection.length; i++) {
                        var instance = wamsUI.Instances.Collection[i];
                        if (instance.Id == instanceId && instance.DeploymentId == deploymentId) {
                            wamsUI.Instances.Collection.splice(i, 1);
                            break;
                        }
                    }

                    // Update deployment
                    var deploymentUI = wamsUI.Deployments.GetUI(deploymentId);
                    if ($(deploymentUI).attr("colspan") == 1) wamsUI.Deployments.RemoveUI(deploymentId);
                    else $(deploymentUI).attr("colspan", parseInt($(deploymentUI).attr("colspan")) - 1);

                    // Remove site states
                    for (var i = 0; i < wamsUI.Sites.Collection.length; i++) {
                        var site = wamsUI.Sites.Collection[i];
                        $(wamsUI.SiteStates.GetUI(site.Id, deploymentId, instanceId)).remove();
                    }
                },
                GetSiteStateIndex: function (deplId,instId) {
                    var index = wamsUI.Deployments.GetInstanceIndex(deplId);
                    var instItems = $("#dashboardHeader>th.instance[data-depl-id='" + deplId + "']");
                    for (var i = 0; i < instItems.length; i++) {
                        if ($(instItems[i]).attr("data-inst-id") == instId) break;
                        index++;
                    }
                    return index;
                }
            },

        Sites:
            {
                Collection: [],
                GetUI: function (siteId)
                { return $("tr.site[data-site-id='" + siteId + "']")[0]; },
                AddUI: function (site)
                {
                    if (site.Source == null) site.Source = "";
                    if (site.Url == null) site.Url = "";
                    var newSiteRow = $("<tr data-site-id=" + site.Id + " data-site-name='" + site.Name + "' data-site-source='" + site.Source + "' data-site-url='" + site.Url + "' onclick='openSiteDetails(this)' class='site updatable' data-site-id='" + site.Id + "'>\
                    <td>" + site.Id + "</td>\
                    <td><i class='icon-globe icon-orange'></i> " + site.Name + "</td></tr>");
                    $(".sites table>tbody").append(newSiteRow);
                    wamsUI.Sites.Collection.push(site);
                    return newSiteRow;
                },
                RemoveUI: function (siteId) {
                    var ui = wamsUI.Sites.GetUI(siteId);
                    if (ui == null) return;
                    $(ui).remove();
                    for (var i = 0; i < wamsUI.Sites.Collection.length; i++) {
                        var site = wamsUI.Sites.Collection[i];
                        if (site.Id == siteId) {
                            wamsUI.Sites.Collection.splice(i, 1);
                            break;
                        }
                    }
                }
            },
        
        SiteStates:
            {
                GetUIsForInstance: function (deploymentId, instanceId)
                { return $(".sitedashboard tbody td.state[data-inst-id='" + instanceId + "'][data-depl-id='" + deploymentId + "']"); },
                GetUI: function (siteId, deploymentId, instanceId)
                { return $(wamsUI.Sites.GetUI(siteId)).children("td.state[data-inst-id='" + instanceId + "'][data-depl-id='" + deploymentId + "']")[0]; },
                AddUI: function (siteInstStatus)
                {
                    var siteRow = $(wamsUI.Sites.GetUI(siteInstStatus.SiteId));
                    var siteStateUI = $("<td class='state' data-inst-id='" + siteInstStatus.InstanceId + "' data-depl-id='" + siteInstStatus.DeploymentId + "' data-original-title='Getting status...'><i class='icon-question-sign'></i></td>");

                    siteStateUI.click(function (event) { event.stopPropagation(); requestContentRefresh(siteInstStatus.DeploymentId, siteInstStatus.InstanceId, siteInstStatus.SiteId); });
                    siteStateUI.hover(
                        function () { $(wamsUI.Instances.GetRelatedCells(siteInstStatus.DeploymentId, siteInstStatus.InstanceId)).addClass("instancehover"); },
                        function () { $(wamsUI.Instances.GetRelatedCells(siteInstStatus.DeploymentId, siteInstStatus.InstanceId)).removeClass("instancehover"); }
                        );
                    var insertIndex = wamsUI.Instances.GetSiteStateIndex(siteInstStatus.DeploymentId, siteInstStatus.InstanceId);
                    $(siteRow).children("td:nth-child(" + (insertIndex + 2) + ")").after(siteStateUI);

                    return siteStateUI;
                }
            }
    };


function requestContentRefresh(deplId, instId, siteId) {
    if (!confirm("Would you like to request a content refresh here?")) return;

    var postData = {
        deploymentId: deplId,
        instanceId: instId,
        siteId: siteId
    };

    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(postData),
        url: 'Services/InstanceControl.svc/RequestContentSync'
    })
    .fail(function (xhr, status, error) {
        stopError("Can't request a content sync on this site/instance!");
    })
    .done(function (data, status, xhr) {
        if (!data.d) return;
        if (data.d.Error != null) stopError(data.d.Error);
        doUpdate(null);
    });

}
function toggleInstanceBusy(deplId, instId) {
    var instCell = wamsUI.Instances.GetUI(deplId, instId);
    if (instCell == null) return;

    var isCurrentlyBusy = $(instCell).hasClass("busyinstance");
    if (isCurrentlyBusy) {
        if (!confirm("Would you like to enable instance?")) return;
    }
    else {
        if (!confirm("Would you like to disable instance?")) return;
    }

    var postData = {
        deploymentId: deplId,
        instanceId: instId,
        busyStatus: !isCurrentlyBusy
    };

    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(postData),
        url: 'Services/InstanceControl.svc/SaveInstanceBusyStatus'
    })
    .fail(function (xhr, status, error) {
        stopError("Can't save instance busy status!");
    })
    .done(function (data, status, xhr) {
        if (!data.d) return;
        if (data.d.Error != null) stopError(data.d.Error);
        doUpdate(null);
    });

}

function GetInstanceStatusInfo(instanceStatus) {
    return {
        Title : ConvertInstanceStatusToWords(instanceStatus),
        CssClass : ConvertInstanceStatusToCssClass(instanceStatus)
    };
}
function ConvertInstanceStatusToWords(instStatus) {
    switch (instStatus) {
        case 0: return "Initialising";
        case 1: return "Starting up";
        case 2: return "Updating";
        case 3: return "Shutting down";
        case 4: return "Error";
        case 5: return "OK!";
        case 6: return "Stale";
        case 7: return "Waiting";
        default: return "-";
    }
}
function ConvertInstanceStatusToCssClass(instStatus) {
    switch (instStatus) {
        case 0: return "";
        case 1: return "icon-orange";
        case 2: return "icon-orange";
        case 3: return "icon-red";
        case 4: return "icon-red";
        case 5: return "icon-green";
        case 6: return "icon-orange";
        case 6: return "icon-orange";
        default: return "";
    }
}

function GetSiteStatusInfo(siteInstStatus) {
    return {
        CssClass: ConvertSiteInstanceStatusToCssClass(siteInstStatus),
        Title: ConvertSiteInstanceStatusToTitle(siteInstStatus)
    };
}

function ConvertSiteInstanceStatusToTitle(siteInstStatus)
{
    switch (siteInstStatus) {
        case 0: return "Initialising";
        case 1: return "Synchronising Content";
        case 2: return "Refreshing Settings";
        case 3: return "OK!";
        case 4: return "Error!";
        case 5: return "Stale";
        case 6: return "Waiting";
        default: return "-";
    }
}
function ConvertSiteInstanceStatusToCssClass(siteInstStatus) {
    switch (siteInstStatus) {
        case 0: return "icon-time";
        case 1: return "icon-refresh animate-rotate icon-orange";
        case 2: return "icon-cog icon-orange";
        case 3: return "icon-ok icon-green";
        case 4: return "icon-exclamation-sign animate-pulse icon-red";
        case 5: return "icon-warning-sign icon-orange";
        case 6: return "icon-upload icon-orange";
        default: return "icon-question-sign";
    }
}


var lastDashboardRefresh = 0;
var dashboardSuspended = false;
var waitingForDashboardRefresh = false;


function setupDashboard(view) {
    if (dashboardSuspended) toggleSuspendDashboard();
}
function updateSiteDashboardStatus(state) {
    var title = "no idea";
    var cssClass = "";

    switch (state) {
        case 1: title = "Online"; cssClass = "label-info"; break;
        case 2: title = "<i class='icon-exclamation-sign icon-white animate-pulse'></i> Error"; cssClass = "label-important"; break;
        case 3: title = "<i class='icon-repeat icon-white animate-rotate'></i> Refreshing"; cssClass = ""; break;
        case 4: title = "Suspended"; cssClass = "label-warning"; break;
    }
    $("#dashboardstatus").html(title);
    $("#dashboardstatus").attr("class","label " + cssClass);
}

function toggleSuspendDashboard() {
    if (dashboardSuspended) {
        dashboardSuspended = false;
        if (!waitingForDashboardRefresh) doUpdate(null);
        else updateSiteDashboardStatus(1);
    }
    else {
        dashboardSuspended = true;
        updateSiteDashboardStatus(4);
    }
}
function doUpdate(callback) {
    waitingForDashboardRefresh = false;
    if (dashboardSuspended) return;
    updateSiteDashboardStatus(3);
    $.ajax({
        method:'post',
        dataType: 'json',
        url: 'Services/InstanceControl.svc/GetDashboardUpdate'
    })
        .fail(function (xhr, status, error) {
            updateSiteDashboardStatus(2);
            stopError("Site statuses are unreachable!");
    })
        .done(function (data, status, xhr) {
            if (data.d.Error != null) stopError(data.d.Error);

            if (lastDashboardRefresh == 99) lastDashboardRefresh = -1;
            var thisDashboardRefresh = lastDashboardRefresh++;

            var sites = data.d.Sites;
            var deployments = data.d.Deployments;
            
            for (var siteIndex = 0; siteIndex < sites.length; siteIndex++) {
                var site = sites[siteIndex];

                if (site.Source == null) site.Source = "";
                if (site.Url == null) site.Url = "";

                var siteRow = wamsUI.Sites.GetUI(site.Id);
                if (siteRow == null) siteRow = wamsUI.Sites.AddUI(site);
                siteRow = $(siteRow);
                siteRow.attr("data-lastRefresh", thisDashboardRefresh);
                siteRow.children("td:nth-child(2)").html("<i class='icon-globe icon-orange'></i> " + site.Name + "</td>");
                siteRow.attr("data-site-name", site.Name);
                siteRow.attr("data-site-source", site.Source);
                siteRow.attr("data-site-url", site.Url);
            }

            for (var deploymentIndex = 0; deploymentIndex < deployments.length; deploymentIndex++) {
                var depl = deployments[deploymentIndex];
                var deploymentUI = wamsUI.Deployments.GetUI(depl.Id);
                if (deploymentUI == null) deploymentUI = wamsUI.Deployments.AddUI(depl);
                $(deploymentUI).attr("class","deplheader deplColor" + $(deploymentUI).index());
                $(deploymentUI).attr("data-lastRefresh", thisDashboardRefresh);
                $(deploymentUI).attr("colspan", depl.Instances.length);
                

                for (var instanceIndex = 0; instanceIndex < deployments[deploymentIndex].Instances.length; instanceIndex++) {
                    var inst = deployments[deploymentIndex].Instances[instanceIndex];
                    inst.Deployment = depl;
                    var instColCell = wamsUI.Instances.GetUI(depl.Id,inst.Id);
                    if (instColCell == null) instColCell = wamsUI.Instances.AddUI(inst);
                    
                    var instanceStatusInfo = GetInstanceStatusInfo(inst.Status);
                    $(instColCell).attr("data-original-title", "#"+ inst.Id + " is " + instanceStatusInfo.Title);
                    $(instColCell).children("i").attr("class", "icon-hdd " + instanceStatusInfo.CssClass);
                    $(instColCell).attr("data-lastRefresh", thisDashboardRefresh);

                    if (inst.IsBusy) $(".sites [data-depl-id='" + depl.Id + "'][data-inst-id='" + inst.Id + "']").addClass("busyinstance");
                    else $(".sites [data-depl-id='" + depl.Id + "'][data-inst-id='" + inst.Id + "']").removeClass("busyinstance");

                    for (var instSiteIndex = 0; instSiteIndex < inst.SiteStatuses.length; instSiteIndex++) {
                        var instSite = inst.SiteStatuses[instSiteIndex];
                        var siteInstStatus = $(wamsUI.SiteStates.GetUI(instSite.SiteId, instSite.DeploymentId, instSite.InstanceId));
                        var statusInfo = GetSiteStatusInfo(instSite.Status);
                        siteInstStatus.children("i").attr("class", statusInfo.CssClass);
                        siteInstStatus.attr("data-original-title", statusInfo.Title);
                        siteInstStatus.attr("data-lastRefresh", thisDashboardRefresh);
                    }
                }
            }

            $(".state[data-lastRefresh!='" + thisDashboardRefresh + "']").each(function (index, element) {
                $(element).attr("data-original-title", "No status found");
            });

            $(".updatable[data-lastRefresh!='" + thisDashboardRefresh + "']").each(function (index, element) {
                if ($(element).hasClass("site")) wamsUI.Sites.RemoveUI($(element).attr("data-site-id"));
                else if ($(element).hasClass("instance")) wamsUI.Instances.RemoveUI($(element).attr("data-depl-id"), $(element).attr("data-inst-id"));
            });

            $(".sites tr td:nth-child(n+2), .sites th").tooltip({ container: 'body' });
            
            updateSiteDashboardStatus(1);
            waitingForDashboardRefresh = true;
            window.setTimeout(function () { doUpdate() }, 5000);
            if (callback != null) callback();
        });
}


function closeNewSiteDialog() {
    $("#newSiteName").val("");
    $("#addSiteDialog .error").hide();
    $("#addSiteDialog .loader").hide();
    hideDialog();
}
function addNewSite(siteName) {

    $("#addSiteDialog .error").hide();
    $("#addSiteDialog .loader").fadeIn();
    var postData = {
        siteName: siteName
    };
    $.ajax({
        type: 'POST',
        data: JSON.stringify(postData),
        contentType: 'application/json',
        dataType: 'json',
        url: 'Services/InstanceControl.svc/AddSite'
    })
    .done(function (data, status, xhr) {
        $("#addSiteDialog .loader").hide();
        if (data == null || data.d == null) {
            closeNewSiteDialog();
        }
        else {
            var errorMsg = $("#addSiteDialog .error");
            errorMsg.html(data.d);
            errorMsg.fadeIn();
        }
    });
}